/* eslint-disable react-hooks/exhaustive-deps */
import React, { ChangeEvent, FC, useState } from "react";
import { Button, Typography, Space, Input, message } from "antd";
import { useNavigate, useParams } from "react-router-dom";
import { useDispatch } from "react-redux";
import { useRequest, useKeyPress, useDebounceEffect } from "ahooks";
import { EditOutlined, LeftOutlined, LoadingOutlined } from "@ant-design/icons";
import EditToolBar from "./EditToolBar";
import useGetPageInfo from "../../../hooks/useGetPageInfo";
import { editPageTitle } from "../../../store/pageInfoReducer";
import { updataQuestionService } from "../../../services/question";
import styles from "./EditHeader.module.scss";
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
const { Title } = Typography;
//显示修改标题
const TitleElem: FC = () => {
  const dispatch = useDispatch();
  const { title } = useGetPageInfo();
  const [editState, setEditState] = useState(false);
  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    const newTitle = event.target.value.trim();
    if (!newTitle) return;
    dispatch(editPageTitle(newTitle));
  }
  if (editState) {
    return (
      <Input
        value={title}
        onPressEnter={() => {
          setEditState(false);
        }}
        onBlur={() => {
          setEditState(false);
        }}
        onChange={handleChange}
      />
    );
  }
  return (
    <Space>
      <Title className={styles.titleStyle} level={4}>
        {title}
      </Title>
      <Button
        icon={<EditOutlined />}
        type="text"
        onClick={() => setEditState(true)}
      />
    </Space>
  );
};
//保存
const SaveButton: FC = () => {
  //保存 pageInfo 和components 组件的全部信息
  const { id } = useParams();
  const pageInfo = useGetPageInfo();
  const { componentList } = useGetComponentInfo();
  //ajax 请求
  const { loading, run: save } = useRequest(
    async () => {
      if (!id) return;
      await updataQuestionService(id, { ...pageInfo, componentList });
    },
    { manual: true }
  );
  //快捷键触发保存
  useKeyPress(["ctrl.s", "meta.s"], (event: KeyboardEvent) => {
    //阻止页面保存
    event.preventDefault();
    if (!loading) save();
  });
  //自动保存 (不是定时保存，增加了防抖功能)
  useDebounceEffect(
    () => {
      save();
    },
    [pageInfo, componentList],
    {
      wait: 1000,
    }
  );

  return (
    <Button
      onClick={save}
      disabled={loading}
      icon={loading ? <LoadingOutlined /> : null}
    >
      保存
    </Button>
  );
};
//发布
const PublishButton: FC = () => {
  const nav=useNavigate()
  const { id } = useParams();
  const pageInfo = useGetPageInfo();
  const { componentList } = useGetComponentInfo();
  //ajax 请求
  const { loading, run: pub } = useRequest(
    async () => {
      if (!id) return;
      await updataQuestionService(id, { ...pageInfo, componentList,isPublished:true, });
    },
    { manual: true ,
      onSuccess(){
        message.success('发布成功')
        nav('/question/stat/'+id)
    }}
  );
  return <Button type="primary" onClick={pub} disabled={loading}>发布</Button>;
};
const EditHeader: FC = () => {
  const nav = useNavigate();
  return (
    <div className={styles["header-wrapper"]}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button
              type="link"
              icon={<LeftOutlined />}
              onClick={() => {
                nav(-1);
              }}
            >
              返回
            </Button>
            <TitleElem />
          </Space>
        </div>
        <div className={styles.main}>
          <EditToolBar />
        </div>
        <div className={styles.right}>
          <Space>
            <SaveButton />
            <PublishButton />
          </Space>
        </div>
      </div>
    </div>
  );
};
export default EditHeader;
